package com.zys.service.impl;

import java.util.Map;
import java.util.Date;
import java.util.HashMap;

import com.zys.pojo.Role;
import com.zys.pojo.User;
import com.zys.dao.UserDao;
import com.zys.entity.QueryInfo;
import com.zys.entity.PageResult;
import com.github.pagehelper.Page;
import com.zys.service.UserService;
import com.github.pagehelper.PageHelper;

import org.springframework.util.DigestUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class UserServiceImpl implements UserService {

  @Autowired
  private UserDao userDao;

  @Override
  public PageResult<User> getUserList(QueryInfo queryInfo) {
    PageHelper.startPage(queryInfo.getCurrentPage(), queryInfo.getPageSize());
    Page<User> page = userDao.findByCondition(queryInfo.getCondition());

    return new PageResult<>(page.getTotal(), page.getResult());
  }

  @Override
  public int changeStateById(Integer id) {
    return userDao.changeStateById(id);
  }

  @Override
  public void add(User user) {
    user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
    user.setState(false);
    user.setRegTime(new Date().getTime());
    user.setRole(new Role(2));
    userDao.add(user);
  }

  @Override
  public void deleteById(Integer id) {
    userDao.deleteById(id);
  }

  @Override
  public int exist(String username) {
    return userDao.findByUserName(username);
  }

  @Override
  public User findUserById(Integer id) {
    return userDao.findUserById(id);
  }

  @Override
  public void edit(User user) {
    userDao.edit(user);
  }

  @Override
  public void changeUserRole(Integer userId, Integer roleId) {
    Map<String, Integer> map = new HashMap<>();
    map.put("uid", userId);
    map.put("rid", roleId);
    userDao.changeUserRole(map);
  }

}
